use actix_web::body::BoxBody;
use actix_web::http::header::ContentType;
use actix_web::{HttpRequest, HttpResponse, Responder};
use serde::Serialize;
use serde_json::json;
use std::fmt::Display;

// JsonResult转换器
pub struct JsonResult<T: Serialize, E: Display>(pub std::result::Result<T, E>);
impl<T: Serialize, E: Display> Responder for JsonResult<T, E> {
    type Body = BoxBody;

    fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> {
        HttpResponse::Ok()
            .content_type(ContentType::json())
            .body(match self.0 {
                Ok(data) => json!({
                    "data":data,
                    "message":"OK",
                    "code":"40001"
                })
                .to_string(),
                Err(err) => json!({
                    "data":"null",
                    "message":format!("Error with {}", err),
                    "code":"50000"
                })
                .to_string(),
            })
    }
}
